package com.pony.iphone.dto;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 消费者和接收者间通信的 DTO
 * @author pony
 * @version 1.0
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class QuestionMessage implements Serializable {  // 🔥 实现 Serializable
    private String messageId;
    private String questionContent;
    private List<String> options;
    private String libraryName;
    private String questionHash;
    private LocalDateTime createTime;

    // 去重相关
    private String deduplicationKey;
    private Duration deduplicationWindow;

    public QuestionMessage(String questionContent, List<String> options, String libraryName) {
        this.messageId = UUID.randomUUID().toString();
        this.questionContent = questionContent;
        this.options = options != null ? options : new ArrayList<>();
        this.libraryName = libraryName;
        this.createTime = LocalDateTime.now();

        // 自动生成题目哈希用于去重
        this.questionHash = generateQuestionHash(questionContent, options);
        this.deduplicationKey = this.questionHash;
        this.deduplicationWindow = Duration.ofHours(24);
    }

    private String generateQuestionHash(String content, List<String> options) {
        try {
            String contentToHash = content + "|" +
                    (options != null ? String.join("|", options) : "");

            java.security.MessageDigest md = java.security.MessageDigest.getInstance("SHA-256");
            byte[] hashBytes = md.digest(contentToHash.getBytes(StandardCharsets.UTF_8));

            StringBuilder hexString = new StringBuilder();
            for (byte b : hashBytes) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();

        } catch (java.security.NoSuchAlgorithmException e) {
            String contentToHash = content + "|" +
                    (options != null ? String.join("|", options) : "");
            return Integer.toHexString(contentToHash.hashCode());
        }
    }
}